﻿exports.save_call = function (req, res) {
    var RESULT_SUCESS = 0;
    var RESULT_ERROR = -1;
    var fs = require("fs");
    var pconfig = require("../common/config").config;
    var DateUtils = require("../common/dateUtils").DateUtils;
    var Commons = require("../common/Commons").Commons;
    var now = new Date();
    var d = DateUtils.dateToString(now);
    var suffix = DateUtils.dateToString(now, "yyyy-MM-dd");
    var fullPath = pconfig.filePathPrefix + pconfig.callFileName + "." + suffix;
    
    var uuid = require('node-uuid');
    if (req.method == "POST") {
        var DBUtils = null;
        var EncryptUtils = require("../common/EncryptUtils").EncryptUtils;
        var isSuccess = true;
        var dbType = pconfig.useDB;
        var url;
        if (dbType == "mongo") {
            url = pconfig.dbUrl;
            DBUtils = require("../common/MongoDBUtils").DBUtils;
        } else if (dbType == "mysql") {
            url = pconfig.mysqlConfig;
            DBUtils = require("../common/MysqlDBUtils").DBUtils;
        }
        var connPromise = DBUtils.getConnection(url, null);
        connPromise.then(function (rdb) {
            var db = rdb.result;
            var datas = req.body;
            var promiseQueryAll = [];
            for (var i = 0; i < datas.length; i++) {
                var data = datas[i];
                               
                data.deviceId = data.deviceId || "unkown_device";
                data.time = DateUtils.dateToString(now);
                //console.log('[' + d + ']' + JSON.stringify(data) + '\n');
                var content = data.deviceId + "_" + data.type + "_" + data.phoneNumber + "_" + data.callTime;
                data._id = EncryptUtils.md5(content);
                console.log("Save Data:" + JSON.stringify(data));
                promiseQueryAll.push(DBUtils.find(db, "call", { _id: data._id }, { index: i, data: data }));
                
                
                
                fs.appendFile(fullPath, '[' + d + ']' + JSON.stringify(data) + '\n', function (err) {
                    if (err) {
                        isSuccess = false;
                        console.log(err);
                    }
                });
            }
            
            
            Promise.all(promiseQueryAll).then(function (dataList) {
                var promiseInsertAll = [];
                for (var j = 0; j < dataList.length; j++) {
                    var r = dataList[j];
                    if (r.result && r.result.length > 0) {
                    } else {
                        promiseInsertAll.push(DBUtils.insert(db, "call", r.object.data, r));
                    }
                }
                Promise.all(promiseInsertAll).then(function (tempList) {
                    for (var j = 0; j < tempList.length; j++) {
                        var r = tempList[j];
                        console.log("insert " + JSON.stringify(r.object.data) + "successful.");
                       
                    }
                    Commons.finishDBAndSetResult(db, dbType, res, true);
                }).catch(function (err) {
                    console.log("insert " + JSON.stringify(data) + " error.\n" + err);                    
                    Commons.finishDBAndSetResult(db, dbType, res, false);
                });            ;
            }).catch(function (err) {
                console.log(err);
                Commons.finishDBAndSetResult(db, dbType, res, false);
            });                
        });
    }    
};